package com.zhongxi.guoyuan.widget.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by Administrator on 2018/4/3.
 */

public class LoadMoreRecyclerView extends RecyclerView {
    private LoadMoreListener loadMoreListener;

    public LoadMoreRecyclerView(Context context) {
        super(context);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        if (state == RecyclerView.SCROLL_STATE_IDLE) {  // 停止滑动
            LayoutManager mLayoutManager = getLayoutManager();
            int lastVisiblePosition = 0;
            if (mLayoutManager instanceof LinearLayoutManager) {
                lastVisiblePosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
            } else if (mLayoutManager instanceof GridLayoutManager) {
                lastVisiblePosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
            }
            //  可见条目大于0
            if (mLayoutManager.getChildCount() > 0 && lastVisiblePosition >= mLayoutManager.getItemCount() - 1
                    && mLayoutManager.getItemCount() > mLayoutManager.getChildCount()) {
                if (loadMoreListener != null) {
                    loadMoreListener.loadingMore();
                }
            }
        }
    }

    public void setOnLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }

    public interface LoadMoreListener {
        void loadingMore();
    }
}
